package com.jet.chat.server;
import java.util.Collection;
import java.util.HashMap;

import com.jet.chat.service.ChatMessage;
import com.jet.chat.service.ChatMessageService;


public class ChatChannel {
	private String channelName;
	private HashMap<String, ChatSession> chatChannel;
	
	public ChatChannel(String channelName) {
		this.channelName = channelName;
		this.chatChannel = new HashMap<String, ChatSession>();
	}

	public String getChannelName() {
		return channelName;
	}
	
	public Collection<ChatSession> getSessions() {
		return chatChannel.values();
	}
	
	public ChatSession getSession(String username) {
		return chatChannel.get(username);
	}
	
	public synchronized void addSession(ChatSession chatSession) {
		for (ChatSession existedSession : getSessions()) {
			ChatMessageService.send(new ChatMessage("server > " + chatSession.getUsername() + " entered channel"), existedSession.getWriter());
		}
		ChatMessageService.send(new ChatMessage("server > you entered channel '" + channelName + "'"), chatSession.getWriter());
		chatChannel.put(chatSession.getUsername(), chatSession);
	}
	
	public synchronized void removeSession(ChatSession chatSession) {
		ChatMessageService.send(new ChatMessage("server > you leaved channel '" + channelName + "'"), chatSession.getWriter());
		chatChannel.remove(chatSession.getUsername());
		for (ChatSession existedSession : getSessions()) {
			ChatMessageService.send(new ChatMessage("server > " + chatSession.getUsername() + " leaved channel"), existedSession.getWriter());
		}
	}
}
